use bevy::prelude::*;

use crate::world_pos_to_block_map_pos;

#[derive(Component)]
pub struct PlayerComponent {
    //朝向 1:右 -1:左
    pub direction: i32,
    pub map_pos: IVec2,
}

impl PlayerComponent {
    pub fn new() -> Self {
        PlayerComponent {
            direction: 1,
            map_pos: IVec2::new(0, 0),
        }
    }

    ///更新地图位置
    pub fn update_map_pos(&mut self, world_pos: &Vec2) {
        let mut pos = world_pos.clone();
        pos.y -= 30.0;
        self.map_pos = world_pos_to_block_map_pos(&pos);
    }
}

#[derive(Component)]
struct PlayerAnimation {
    pub timer: Timer,
}

///玩家插件
pub struct PlayerPlugin;

impl Plugin for PlayerPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, spawn_player)
            .add_systems(Update, move_player)
            .add_systems(Update, follow_player)
            .add_systems(Update, animate_player); // 添加动画系统
    }
}

fn spawn_player(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
    let idle_texture_handle = asset_server.load("texture/player/idle.png");
    let idle_layout = TextureAtlasLayout::from_grid(UVec2::new(16, 16), 4, 3, None, None);
    let texture_atlas_layout_handle = texture_atlas_layouts.add(idle_layout);
    commands.spawn((
        Sprite {
            image: idle_texture_handle,
            texture_atlas: Some(TextureAtlas {
                layout: texture_atlas_layout_handle,
                index: 0,
            }),
            ..Default::default()
        },
        Transform::from_translation(Vec3::new(0., 0., 10.)).with_scale(Vec3::splat(4.0)),
        PlayerComponent::new(),
        PlayerAnimation {
            timer: Timer::from_seconds(0.1, TimerMode::Repeating),
        },
    ));
}

///使用ADWS控制玩家移动
fn move_player(
    time: Res<Time>,
    keyboard_input: Res<ButtonInput<KeyCode>>,
    query: Single<(&mut PlayerComponent, &mut Transform)>,
) {
    let mut direction = Vec2::ZERO;

    if keyboard_input.pressed(KeyCode::KeyA) {
        direction.x -= 1.0;
    }
    if keyboard_input.pressed(KeyCode::KeyD) {
        direction.x += 1.0;
    }
    if keyboard_input.pressed(KeyCode::KeyW) {
        direction.y += 1.0;
    }
    if keyboard_input.pressed(KeyCode::KeyS) {
        direction.y -= 1.0;
    }

    let move_pos = direction.normalize_or_zero();

    let (mut player, mut transform) = query.into_inner();
    if move_pos != Vec2::ZERO {
        transform.translation.x += move_pos.x * PLAYER_SPEED * time.delta_secs();
        transform.translation.y += move_pos.y * PLAYER_SPEED * time.delta_secs();
        player.update_map_pos(&transform.translation.xy());
    }
    if move_pos.x != 0.0 {
        player.direction = if move_pos.x > 0.0 { 1 } else { -1 };
    }
}

fn animate_player(
    time: Res<Time>,
    query: Single<(&mut Sprite, &mut PlayerAnimation, &mut PlayerComponent)>,
) {
    let (mut sprite, mut anim, player) = query.into_inner();
    anim.timer.tick(time.delta());
    if anim.timer.finished() {
        if let Some(texture_atlas) = &mut sprite.texture_atlas {
            texture_atlas.index = (texture_atlas.index + 1) % 4; // 每行4帧，默认先用第一行
            if player.direction == -1 {
                sprite.flip_x = true;
            } else {
                sprite.flip_x = false;
            }
        };
    }
}

///相机跟随玩家
fn follow_player(
    player: Single<&Transform, With<PlayerComponent>>,
    camera: Single<&mut Transform, (With<Camera>, Without<PlayerComponent>)>,
) {
    let player_transform = *player;
    let mut camera_transform = camera;
    //使用线性插值让相机跟随玩家
    camera_transform.translation = camera_transform
        .translation
        .lerp(player_transform.translation, 0.1);
}

// 假设 PLAYER_SPEED 是一个常量
const PLAYER_SPEED: f32 = 200.0;
